package com.slashmanx.socialwall;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.WallpaperManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.widget.AdapterView.OnItemClickListener;
import android.view.View.OnClickListener;

import com.slashmanx.helpers.Downloader;
import com.slashmanx.helpers.Utilities;


public class SocialWallActivity extends Activity 
{

    public ArrayList<String> dl_pics = new ArrayList<String>();
    ArrayList<SocialPicture> pictures = new ArrayList<SocialPicture>();
    ImageView selectedImage;
    ProgressBar imageProgressBar;
    int selectedIndex = 0;
    static String sw_token;
    static int userID;
    private Intent intent;
    Handler handler=new Handler() {
		@Override
		public void handleMessage(Message msg) {
			imageProgressBar.incrementProgressBy(1);
		}
	};


    Gallery gallery;

    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        // Restore preferences
        SharedPreferences settings = getPreferences(0);
        sw_token = settings.getString("UserToken", null);
        userID = settings.getInt("UserID", -1);
        setContentView(R.layout.main);
        
        gallery = (Gallery)findViewById(R.id.SocialGallery);
        selectedImage = (ImageView)findViewById(R.id.selectedImage);
        imageProgressBar = (ProgressBar)findViewById(R.id.imageProgress);
        imageProgressBar.setMax(5);
        imageProgressBar.setVisibility(View.INVISIBLE);
        imageProgressBar.setProgress(0);
        gallery.setAdapter(new ImageAdapter(this, dl_pics));
        
        gallery.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView parent, View v, int position, long id) {
                selectedImage.setImageURI(Uri.parse("file://"+dl_pics.get(position)));
                selectedIndex = position;
            }
        });
        
        selectedImage.setOnClickListener(new OnClickListener() 
        {
			public void onClick(View v) 
			{
				Utilities.setWallpaper(SocialWallActivity.this, getApplicationContext(), dl_pics.get(selectedIndex));
			}
        });
        registerForContextMenu(selectedImage); 
        
        if(sw_token == null || userID == -1)
        {
        	 //Preparing views
            LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
            View layout = inflater.inflate(R.layout.dialog_layout, (ViewGroup) findViewById(R.id.layout_root));
        //layout_root should be the name of the "top-level" layout node in the dialog_layout.xml file.
            final EditText username = (EditText) layout.findViewById(R.id.username);
            final EditText password = (EditText) layout.findViewById(R.id.password);

            //Building dialog
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setView(layout);
            builder.setPositiveButton("Login", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                	ArrayList<String> info = new ArrayList<String>(2);
                	info.add(username.getText().toString());
                	info.add(password.getText().toString());
                	new PostLoginTask().execute(info);
                    dialog.dismiss();
                    //save info where you want it
                }
            });
            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            AlertDialog dialog = builder.create();
            dialog.show();
        }

        
        else
        {
            intent = new Intent(this, SocialWallService.class);
            
            startService(intent);
            registerReceiver(broadcastReceiver, new IntentFilter(SocialWallService.BROADCAST_ACTION));

        	//doStartTask();
        }
    }
    
    public void startProgress()
    {
    	imageProgressBar.setProgress(0);
    	imageProgressBar.setVisibility(View.VISIBLE);
    }
    @Override  
    public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {  
    	super.onCreateContextMenu(menu, v, menuInfo);  
    	menu.setHeaderTitle("Image Actions");  
    	menu.add(0, v.getId(), 0, "Delete");
    }  
    
    @Override  
    public boolean onContextItemSelected(MenuItem item) {  
        if(item.getTitle()=="Delete") {
        	File file = new File(dl_pics.get(selectedIndex));
        	boolean deleted = file.delete();
        	dl_pics.remove(selectedIndex);
        	selectedImage.setImageURI(null);
        	BaseAdapter  theAdapter = (BaseAdapter) gallery.getAdapter();
        	theAdapter.notifyDataSetChanged();
        }    
        else {
        	return false;
        }  
        
        return true;  
    }
    
    public boolean onCreateOptionsMenu(Menu menu) 
    { 
        menu.add(1,1,1,"Settings");
        menu.findItem(1).setIcon(android.R.drawable.ic_menu_manage);
        menu.add(1,2,1,"Delete All");
        menu.findItem(2).setIcon(android.R.drawable.ic_delete);
        return super.onCreateOptionsMenu(menu);  
      } 
    
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId()) {
            case 1:
            	Intent pIntent = new Intent(this, Preferences.class);
            	startActivity(pIntent);
            	break;
            case 2:
            	File sdCard = Environment.getExternalStorageDirectory();
                File dir = new File(sdCard.getAbsolutePath() + "/SocialWall/Pictures/");
                
                dir.mkdirs();
                
                if (dir.listFiles().length > 0) 
                {
                	for (File file : dir.listFiles()) {
                		file.delete();
                		dl_pics.remove(file.getAbsolutePath());
                		
                		BaseAdapter  theAdapter = (BaseAdapter) gallery.getAdapter();
                    	theAdapter.notifyDataSetChanged();
                	}
                	selectedImage.setImageURI(null);
                 }
            	
        }
        return true;
    }

    
	public void onDestroy() {
		super.onDestroy();
		stopService(intent);
		try
		{
			unregisterReceiver(broadcastReceiver);
		}
		catch(IllegalArgumentException iae)
		{
			// Ignore Exception
		}
	}

    
    public class ImageAdapter extends BaseAdapter {
        int mGalleryItemBackground;
        private Context mContext;
        ArrayList<String> gal_pics;

        

        public ImageAdapter(Context c, ArrayList<String> gal_pics) {
            this.mContext = c;
            this.gal_pics = gal_pics;
            populateGallery();
            TypedArray attr = mContext.obtainStyledAttributes(R.styleable.GalleryStyle);
            mGalleryItemBackground = attr.getResourceId(
                    R.styleable.GalleryStyle_android_galleryItemBackground, 0);
            attr.recycle();
        }
        
        public void populateGallery()
        {
        	gal_pics.clear();
        	File sdCard = Environment.getExternalStorageDirectory();
            File dir = new File(sdCard.getAbsolutePath() + "/SocialWall/Pictures/");
            
            dir.mkdirs();
            
            if (dir.listFiles().length > 0) 
            {
            	for (File file : dir.listFiles()) {
            		gal_pics.add(file.getAbsolutePath());
            	}
             }
        }

        public int getCount() {
            return gal_pics.size();
        }

        public Object getItem(int position) {
            return gal_pics.get(position);
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView = new ImageView(mContext);

            imageView.setImageURI(Uri.parse("file://"+gal_pics.get(position)));
            imageView.setLayoutParams(new Gallery.LayoutParams(150, 100));
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imageView.setBackgroundResource(mGalleryItemBackground);

            return imageView;
        }
    }
    
    public void addToGallery(String filename)
    {
    	//ImageView swView = (ImageView) findViewById(R.id.swallpaper);
    	//Toast.makeText(getApplicationContext(), filename, Toast.LENGTH_SHORT).show();
    	dl_pics.add(filename);
    	BaseAdapter  theAdapter = (BaseAdapter) gallery.getAdapter();
    	theAdapter.notifyDataSetChanged();
    }
    
    public void doStartTask()
    {
    	startProgress();
    	new DownloadPicturesTask().execute("http://slashmanx.com/SocialWall/getPictures.php");
    }
    
    class DownloadPicturesTask extends AsyncTask<String, String, Long>
    {
    	     protected Long doInBackground(String... url) 
    	     {
    	    	 try 
    	     	{
    	    		 List<NameValuePair> params = new ArrayList<NameValuePair>(2);
    	 			
    	 	        params.add(new BasicNameValuePair("userID", Integer.toString(userID)));
    	 	        params.add(new BasicNameValuePair("sw_token", sw_token));
    	 	        
    	 	        Log.d("USERID", ""+ userID);
    	 	        Log.d("sw_token", sw_token);
    	     		
    	     		JSONObject 	jObject = getJSONfromURL(url[0], params);
    	     		pictures.clear();
    	     		String pic_url, pic_author, pic_source;
    	     		
    	     		if(jObject != null)
    	     		{
    	     			JSONObject  picturesObject 	= jObject.getJSONObject("pictures");
    	     			JSONArray 	pictureArray 	= picturesObject.getJSONArray("picture");
    	     		
    	     		
    	     			for(int i = 0; i < pictureArray.length(); i++)
    	     			{
    	     				pic_url = pictureArray.getJSONObject(i).getString("url").toString();
    	     				pic_author = pictureArray.getJSONObject(i).getString("author").toString();
    	     				pic_source = pictureArray.getJSONObject(i).getString("source").toString();
    	     				SocialPicture temp = new SocialPicture(pic_url, pic_source, pic_author);
    	     				//temp.setUrl(pictureArray.getString(i));    				
    	     				pictures.add(temp);
    	     			}
    	     		}
    	 		} 
    	     	catch (Exception e) {
    	 			// TODO Auto-generated catch block
    	 			Log.d("Error", "Error");
    	 		}
    	     	DownloadPicturesTask task = new DownloadPicturesTask();
    	     	for(SocialPicture p : pictures)
    	     	{
    	     		Log.d("URL", (p.getUrl()));
    	     	}
    	         int count = pictures.size();
    	         Log.d("Length of pictures", ""+ count);
    	         String fileLocation = "";
    	         for (int i = 0; i < count; i++) 
    	         {
	        		 fileLocation = Downloader.DownloadFile(pictures.get(i));
    	             publishProgress(fileLocation);  
    	         }
    	         
    	         return Long.decode(Integer.toString(count));
    	     }

    	     protected void onProgressUpdate(String... newFiles) 
    	     {
    	         if(newFiles[0] != null)
    	         {
    	        	 handler.sendMessage(handler.obtainMessage());
    	        	 addToGallery(newFiles[0]);
    	         }
    	     }

    	     protected void onPostExecute(Long result) 
    	     {
    	    	 int rand = Utilities.getRandomNumber(0, pictures.size()-1);
    	    	 File sdCard = Environment.getExternalStorageDirectory();
    	         File dir = new File(sdCard.getAbsolutePath() + "/SocialWall/Pictures/");
    	         Utilities.setWallpaper(SocialWallActivity.this, getApplicationContext(), dir + "/" + pictures.get(rand).getName());
/*      	         Bitmap o = BitmapFactory.decodeFile(dir + "/" + pictures.get(rand).getName());

    	         WallpaperManager myWallpaperManager = WallpaperManager.getInstance(getApplicationContext());
    	         try 
    	         {
    	                 myWallpaperManager.setBitmap(o);   	
    	         } 
    	         catch (IOException e) 
    	         {
    	                 // TODO Auto-generated catch block
    	                 e.printStackTrace();
    	         }

*/    	         //showDialog("Downloaded " + result + " bytes");
    	     }
    	 }
    class PostLoginTask extends AsyncTask<ArrayList<String>, ArrayList<String>, ArrayList<String>>
    {
    	     protected ArrayList<String> doInBackground(ArrayList<String>... loginInfo) 
    	     {
    	    	 ArrayList<String> userInfo = new ArrayList<String>(2);
    	    	 String username = loginInfo[0].get(0);
 	     		 String password = loginInfo[0].get(1);
 	     		 List<NameValuePair> params = new ArrayList<NameValuePair>(2);
 				
 		        params.add(new BasicNameValuePair("username", username));
 		        params.add(new BasicNameValuePair("password", password));
    	    	 try 
    	     	{
    	     		
    	     		JSONObject 	jObject = getJSONfromURL("http://slashmanx.com/SocialWall/androidLogin.php", params);
    	     		
    	     		
    	     		
    	     		if(jObject != null)
    	     		{
    	     			JSONArray  userArray 	= jObject.getJSONArray("user");
    	     			
    	     		
    	     		
    	     			for(int i = 0; i < userArray.length(); i++)
    	     			{
    	     				userInfo.add(userArray.getJSONObject(i).getString("id").toString());
    	     				userInfo.add(userArray.getJSONObject(i).getString("sw_token").toString());
    	     			}
    	     			
    	     		}
    	 		} 
    	     	catch (Exception e) {
    	 			// TODO Auto-generated catch block
    	 			Log.d("Error", "Error");
    	 		}
    	    	 
    	    	 //publishProgress(userInfo);
    	         
    	         return userInfo;
    	     }

    	     protected void onProgressUpdate(ArrayList<String>... newFiles) 
    	     {
    	         
    	     }

    	     protected void onPostExecute(ArrayList<String> userInfo) 
    	     {
    	    	 SharedPreferences settings = getPreferences(0);
    	         SharedPreferences.Editor editor = settings.edit();
    	         editor.putInt("UserID", Integer.parseInt(userInfo.get(0)));
    	         editor.putString("UserToken", userInfo.get(1));
    	         editor.commit();
    	         
    	         userID = Integer.parseInt(userInfo.get(0));
    	         sw_token = userInfo.get(1);
    	         
    	         Toast.makeText(getApplicationContext(), "Logged In Successfully", Toast.LENGTH_SHORT);
    	         
    	         doStartTask();
    	     }
    	 }
	public static JSONObject getJSONfromURL(String url, List<NameValuePair> params) {

		//initialize
		InputStream is = null;
		String result = "";
		JSONObject jArray = null;

		//http post
		try{
			
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(url);
	        httppost.setEntity(new UrlEncodedFormEntity(params));
	        
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();

		}catch(Exception e){
			// Connection error
			Log.e("CONNECTION!!!!", "Connection Error: "+ url+  e.toString() );
			return null;
		}

		//convert response to string
		try{
			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			result=sb.toString();
		}catch(Exception e){
			// reading error
			Log.e("READING!!!!", "Reading Error");
		}

		//try parse the string to a JSON object
		try{
	        	jArray = new JSONObject(result);
		}catch(JSONException e){
			//JSON Parsing Error
			Log.e("PARSING!!!!", "Parsing Error "+ e.getLocalizedMessage());
		}

		return jArray;
	}
	
    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() 
    {
        @Override
        public void onReceive(Context context, Intent intent) 
        {
        	doStartTask();
        }
    };    


}
